package com.liuhaoqi.raletiveblog.controller;

import com.github.pagehelper.PageInfo;
import com.liuhaoqi.raletiveblog.entity.Blog;
import com.liuhaoqi.raletiveblog.entity.Category;
import com.liuhaoqi.raletiveblog.entity.dto.BlogDto;
import com.liuhaoqi.raletiveblog.result.PageResult;
import com.liuhaoqi.raletiveblog.service.BlogService;
import com.liuhaoqi.raletiveblog.service.CategoryService;
import com.liuhaoqi.raletiveblog.utils.MarkdownUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author liuhaoqi
 * @Date 2020/4/18 17:30
 * @Version 1.0
 */
@Controller
public class DetailController {
    @Autowired
    BlogService blogService;
    @Autowired
    CategoryService categoryService;


    @GetMapping("/detail")
    public String toDetail() {
        return "detail";
    }

    @GetMapping("/detailBlog/{id}")
    public String toDetailBlog1(@PathVariable Long id, Model model, @RequestParam(defaultValue = "1",value = "pageNum") String pageNum,
                               @RequestParam(defaultValue = "3",value = "pageSize") String pageSize,
                               HttpServletResponse response) {

        //访问一次这个id就增加一次访问量
        BlogDto blogDto = blogService.getDetailBlog(id);
        BlogDto blogDtoCopy = new BlogDto();
        BeanUtils.copyProperties(blogDto,blogDtoCopy);
//        String s = MarkdownUtils.markdownToHtmlExtensions(blogDtoCopy.getContent());
//        blogDtoCopy.setContent(s);
        model.addAttribute("blog",blogDtoCopy);
        //添加一个响应头信息
        response.addHeader("blogId",String.valueOf(id));
        //分类导航,查出所有分类返回给前端
        List<Category> categoryList = categoryService.getCategoryList();
        model.addAttribute("categoryList",categoryList);
        PageInfo<BlogDto> blogList = blogService.getBlogList(pageNum, pageSize);
        model.addAttribute("blogs",blogList);
        List<BlogDto> blogListNoFenYe = blogService.getBlogListNoFenYe();
        model.addAttribute("blogListNoFenYe",blogListNoFenYe);
        return "detail";
    }

    @GetMapping("/getVisitorNumByBlogId")
    @ResponseBody
    public String getVisitorNumByBlogId(@RequestParam("blogId") Long blogId) {
        int flag = blogService.updateDetailBlogViewsById(blogId);
        int views = blogService.getBlogViewsById(blogId);
        return String.valueOf(views);
    }
}
